package com.wutao.panzh.admin.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.panzh.UtilEntity.ResultVO;
import com.panzh.entity.UserAdminInfo;
import com.panzh.myconst.UserContst;
import com.panzh.util.StringUtil;
import com.panzh.wutao.util.ObjectUtil;
import com.wutao.panzh.coust.WebConst;
import com.wutao.panzh.service.UserAdminService;
import com.wutao.panzh.util.HttpCilentUtil;
import com.wutao.panzh.util.JwtUtil;
import io.jsonwebtoken.SignatureException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class UserAdminController {

    @Reference
    private UserAdminService userAdminService;

    @RequestMapping("/dologin")
    @ResponseBody
    public Object getUserAdmin(UserAdminInfo userAdminInfo, HttpSession session) throws JsonProcessingException {
        String tel = userAdminInfo.getPhoneNum();
        UserAdminInfo userAdminInfoBytel = userAdminService.getUserAdminInfoBytel(tel);
        if (userAdminInfoBytel != null) {
            if (userAdminInfoBytel.getPasswd().equals(StringUtil.md5(userAdminInfo.getPasswd()))) {
                //验证通过,并吧登录的信息放入session域中；
                //session.setAttribute(UserContst.USER_ADMIN_INFO_IS_EXIST,userAdminInfoBytel);
                //这里就应该产生token；
                //进行加密，得到Token;
                //得到对象属性转换成的map;
                Map tranfMap = ObjectUtil.ObjectTranfMap(userAdminInfoBytel, UserAdminInfo.class);
                String token = JwtUtil.encode(WebConst.WEB_PASSWORD_KEY, tranfMap, StringUtil.md5("127.0.0.1"));
                //把token返回到前端的页面;
                return new ResultVO<String>(ResultVO.SUCCESS, ResultVO.NO_MSG, token);
            } else {
                return new ResultVO<String>(ResultVO.FAILED, UserContst.PASSWORD_ERROR, ResultVO.NO_DATA);
            }
        } else {
            return new ResultVO<String>(ResultVO.FAILED, UserContst.ACCOUNT_DOES_NOT_EXIST, ResultVO.NO_DATA);
        }
    }

    //    HttpCilentUtil.doGet(WebConst.PANZH_ADMIN_PRIFIX + "decode?token=" + oldToken + "?ipAddr=" + ipAddr)
    @RequestMapping("/decode")
    @ResponseBody
    public String decode(String token){
        try {
            Map map = JwtUtil.decode(WebConst.WEB_PASSWORD_KEY, token, StringUtil.md5("127.0.0.1"));
            return WebConst.JWT_IS_SECESS;
        } catch (SignatureException e) {
            e.printStackTrace();
            return WebConst.JWT_IS_FAIL;
        }
    }
}
